import http from '../../utils/http.js'
import BuyCart from '../../utils/buycar.js'
import moment from '../../utils/moment.js'
const app = getApp()

Page({
  data: {
    wxPhone:'',//从微信授权获取的手机号
    page:1,
    total:0,
    pageSize:8,
    imgDomain: app.globalData.imgDomain,
    goods:[],
    cartCount:0,
    lyTotal:0,
    lyGoods:[],
    wgtsGoods:[],
    wgtsTotal:[],
    good:{
      attrList:[]
    },
    selectedAttr:{},
    imgHeight:0,
    activeTab:1,
    userInfo: {},
    hasUserInfo: false,
    isViewDetail:false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isLogin:false,
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 200,
    ads:[],
    recommends:[],
    defaultcakeImg:'/resource/image/default_cake.png',
    swiperHeight:300,
    modalHidden:true,
    couponModalHidden:true,
    couponImg: 'http://image.fuyj.com.cn/coupon.png?time=' + new Date().getTime()
  },
  viewNoticeImg(){
    wx.previewImage({
      current: "http://image.fuyj.com.cn/images/notice/IMG_3408.JPG", // 当前显示图片的http链接
      urls: ["http://image.fuyj.com.cn/images/notice/IMG_3408.JPG"] // 需要预览的图片http链接列表
    })
  },
  couponModalConfirm(){
    let me=this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      me.setData({
        isLogin:true
      })
      return;
    }
    http.request({
      url: 'coupon/sendSpeCoupon/' + userId+"/113",
      loadTip: '正在请求',
      success: res => {
        wx.showToast({
          icon: 'success',
          title: '领取成功'
        })
        wx.setStorageSync('getCoupon',true);
        me.setData({
          couponModalHidden: true
        });
      }
    });
  },
  couponModalCandel(){
    this.setData({
      couponModalHidden: true
    });
  },
  modalConfirm(){
    this.setData({
      modalHidden:true
    });
  },
  modalCandel(){
    this.setData({
      modalHidden: true
    });
  },
  initNoticeShow(){
    if (moment().isBefore('2019-02-08')){
      this.setData({
        modalHidden: false
      });
    }
    if (moment().isAfter('2019-10-25') && moment().isBefore('2019-11-03')){
      let getCoupon = wx.getStorageSync("getCoupon");
      if (!getCoupon){
        this.setData({
          couponModalHidden:false
        })
      }
    }else{
      wx.removeStorageSync("getCoupon");
    }
  },
  previewImg(){
    wx.previewImage({
      urls: ["http://image.fuyj.com.cn/images/send.jpg?v=2.0"]
    })
  },
  openGroupBuy(){
    wx.navigateTo({
      url: '../group/group_buy'
    })
  },
  openMap(){
    wx.openLocation({
      latitude: 32.012585,
      longitude: 118.787655,
      name:'浮遇纪线上店',
      address:'南京市秦淮区剪子巷与箍桶巷交叉口西南100米'
    })
  },
  //事件处理函数
  openUserInfo(){
    if(!app.isBind()){
      this.setData({
        isLogin:true
      });
      return;
    }
    if (!this.data.canIUse){
      return;
    }
    wx.navigateTo({
      url: '../my/my'
    })
  },
  goCart(){
    if (!app.isBind()) {
      this.setData({
        isLogin: true
      });
      return;
    }
    wx.navigateTo({
      url: '../buycar/buycar'
    })
  },
  getSmsCode(e){
    let me=this;
    let phone = e.detail;
    if(phone){
      me.setData({
        wxPhone: phone
      });
    }
    if (!me.data.wxPhone){
      return;
    }
    http.request({
      url: 'user/smsCode/'+me.data.wxPhone,
      loadTip:'正在加载',
      method:'get',
      success: res => {
        if(res){
          wx.showToast({
            icon:'success',
            title: '验证码已发送'
          })
        }
      }
    });
  },
  bindAccount(e){
    let me=this;
    if (!e.detail.phone) {
      wx.showToast({
        icon:'none',
        title: '请输入手机号',
      })
      return;
    }
    if (!e.detail.smscode) {
        wx.showToast({
          icon: 'none',
          title: '请输入短信验证码',
        })
        return;
    }
    http.request({
      url: 'user/register2',
      loadTip: '正在请求',
      data: {
        phone: e.detail.phone,
        smscode: e.detail.smscode,
        wxkey: app.getSessionKey(),
        sex: 1
      },
      success: res => {
        me.setData({
          isLogin: false
        });
        wx.setStorageSync("userId", res.userId);
        wx.setStorageSync("phone", res.userName);
        me.getCouponList();
        setTimeout(()=>{
          me.updateUser();
          me.getCartCount();
        },200)
      }
    });
  },
  getPhoneNumber(e){
    let me =this;
    http.request({
      url:'user/getPhoneNumberOfWx2',
      loadTip:'授权中',
      data:{
        encrypData:e.detail.encryptedData,
        iv:e.detail.iv,
        wxKey: app.getSessionKey()
      },
      success:res=>{
        console.log(res);
        let phoneInfo = JSON.parse(res);
        me.setData({
          wxPhone: phoneInfo.phoneNumber
        });
      }
    });
  },
  goDetail(e){
    let goodsId = e.currentTarget.dataset.goodsId
    if(!goodsId){
      return;
    }
    wx.navigateTo({
      url: '../detail/detail?id=' + goodsId
    })
  },
  viewDetail(e){
    if (!app.isBind()) {
      this.setData({
        isLogin: true
      });
      return;
    }
    this.loadGoodDetail(e);
    this.setData({
      isViewDetail:true
    });
  },

  addCart(e){
    let me = this;
    let userId = wx.getStorageSync("userId");
    BuyCart.add(this.data.selectedAttr.goodsAttrId, 1, userId,(res)=>{
      me.getCartCount();
      this.setData({
        isViewDetail: false
      });
    });
  },

  getCartCount(){
    let me=this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      me.setData({
        cartCount: 0
      });
      return;
    }
    http.request({
      url: 'cart/count/' + userId,
      method:'get',
      success:res=>{
        me.setData({
          cartCount:res
        });
      }
    });
  },
  getHomeBanner(){
    let me=this;
    http.request({
      url: 'home/getHomeData',
      method: 'get',
      success: res => {
        me.setData({
          ads: res.ads,
          recommends:res.recommends
        });
      }
    });
  },

  closeBox(e){
    this.setData({
      isViewDetail: false
    });
  },
  clickDetail(e){},
  selectWeight(e){
    this.setData({
      selectedAttr: e.currentTarget.dataset.select
    });
  },
  switchTab(e){
    this.data.page = 1;
    this.setData({
      activeTab: e.currentTarget.dataset.type,
      page:1
    },()=>{
      if (this.data.activeTab == 5 && this.data.goods.length == 0){
        this.loadGoods();
      }
      if (this.data.activeTab == 24 && this.data.lyGoods.length==0){
        this.loadGoods();
      }
      if (this.data.activeTab == 26 && this.data.wgtsGoods.length == 0) {
        this.loadGoods();
      }
    });
  },
  loadMore(){
    if (this.data.activeTab == 5 && this.data.goods.length >= this.data.total) {
      wx.showToast({
        icon: 'none',
        title: '没有更多商品哦',
      })
      return;
    }
    if (this.data.activeTab == 24 && this.data.lyGoods.length >= this.data.lyTotal) {
      wx.showToast({
        icon: 'none',
        title: '没有更多商品哦',
      })
      return;
    }
    this.setData({
      page:this.data.page+1
    },()=>{
      this.loadGoods();
    });
  },
  loadGoodDetail(e){
    let me=this;
    http.request({
      url:'good/getGoodAttrByIdForWx/'+e.currentTarget.dataset.goodsId,
      method:'get',
      success:res=>{
        me.setData({
          good:{
            attrList: res
          },
          selectedAttr: res[0]
        });
      }
    });
  },
  loadGoods(){
    let me=this;
    http.request({
      url:'good/getSaleList',
      loadTip: '正在加载',
      data:{
        catId: me.data.activeTab,
        belongTo:103,
        page:me.data.page,
        pageSize:8,
        saling:1
      },
      success:res=>{
        me.genGoodDatas(res);
      }
    });
  },
  genGoodDatas(data){
    let me=this;
    console.log(data);
    if (me.data.activeTab == 5){
      data.list.forEach(good => {
        me.data.goods.push(good);
      });
    } else if (me.data.activeTab == 24){
      data.list.forEach(good => {
        me.data.lyGoods.push(good);
      });
    } else if (me.data.activeTab == 26) {
      data.list.forEach(good => {
        me.data.wgtsGoods.push(good);
      });
    }
    if (me.data.activeTab == 5) {
      me.setData({
        total: data.total,
        goods: me.data.goods
      });
    } else if (me.data.activeTab == 24) {
      me.setData({
        lyTotal: data.total,
        lyGoods: me.data.lyGoods
      });
    } else if (me.data.activeTab == 26) {
      me.setData({
        wgtsTotal: data.total,
        wgtsGoods: me.data.wgtsGoods
      });
    }
  },
  onPullDownRefresh(){
    console.log("refresh");
  },
  onReachBottom(){
    if (this.data.activeTab == 5 || this.data.activeTab == 24){
      this.loadMore();
    }
  },
  onLoad: function () {
    let me = this;
    const column = 2;
    let systemInfo = wx.getSystemInfoSync();
    let width = systemInfo.screenWidth;
    let height = (width - (column + 1) * 10) / column;
    let swiperH = 632 * width / 889;
    me.setData({
      imgHeight:height,
      swiperHeight: swiperH
    });
    me.updateUser();
    app.checkSession();
    me.getCouponList();
    me.initNoticeShow();
  },
  updateUser(){
    let me=this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      return;
    }
    wx.getSetting({
      success: function (res) {
        console.log(res);
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success: function (res) {
              http.request({
                url:'user/saveTx',
                data:{
                  userId:userId,
                  icon: res.userInfo.avatarUrl,
                  nickname: res.userInfo.nickName
                },
                success:res=>{
                  console.log(res);
                }
              });
            }
          })
        }else{
          me.setData({
            canIUse:false
          });
        }
      }
    })
  },
  getCouponList() {
    let me = this;
    let userId = wx.getStorageSync("userId");
    if(!userId){
      return;
    }
    http.request({
      url: 'coupon/getCouponByUserId/' + userId,
      loadTip: '加载中',
      success: res => {
        if(res && res.length>0){
          let couponNames = "";
          res.forEach((item)=>{
            couponNames += "【" + item.name+"】,"
          });
          couponNames = couponNames.substr(0, couponNames.length-1);
          wx.showModal({
            title: '优惠券',
            content: '您有 ' + res.length + ' 张优惠券' + couponNames,
            cancelText: '先逛逛',
            confirmText: '立即查看',
            success:res=>{
              if(res.confirm){
                wx.navigateTo({
                  url: '../coupon/coupon'
                })
              }
            }
          })
        }
      }
    });
  },
  onShow(){
    this.getHomeBanner();
    this.getCartCount();
  },
  getUserInfo: function(e) {
    console.log(e);
    this.setData({
      userInfo: e.detail.userInfo,
      canIUse:true
    })
    let userId = wx.getStorageSync("userId");
    http.request({
      url: 'user/saveTx',
      data: {
        userId: userId,
        icon: e.detail.userInfo.avatarUrl,
        nickname: e.detail.userInfo.nickName
      },
      success: res => {
        wx.navigateTo({
          url: '../my/my',
        })
      }
    });
  }
})
